<?php

namespace App\Http\Controllers\App;

use App\Exceptions\FailException;
use App\Models\City;
use App\Models\Common;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CommonController extends Controller
{
    /**
     * 上传文件接口
     * @param Request $request
     * @return array
     * @throws FailException
     */
    public function uploadFile(Request $request)
    {
        $data = [];
        if ($files = $request->file()) {

            $path = sprintf("/data/upload/%s/%s/%s", date('Y', time()), date('m', time()),
                date('d', time()));
            $filePath = base_path('public' . $path);
            foreach ($files as $file) {
                $fileName = \Illuminate\Support\Str::random(16) . '.' . $file->getClientOriginalExtension();
                $file->move($filePath, $fileName);
                $data[] = env('apiUrl') .'/'. $path .'/'. $fileName;
            }
            return $data;
        }
        throw new FailException("上传失败");

    }

    // todo 发送短信验证码

    /**
     * 发送短信
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws FailException
     */
    public function sendSmsCode(Request $request)
    {

        $this->validate($request, [
            'phone' => [

                ['required', 'regex:/^1[345789][0-9]{9}$/']
            ]], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机号格式错误'
        ]);

        $type = request('type', 1);
        $phone = request('phone');
        $smsMsg = new Common();
        $res = $smsMsg->sendSmsCode($phone, $type);
        return $this->success($res);
    }


    public function city()
    {
        $pid = request('pid', 100000);
        return City::select('id','name')->where('pid', $pid)->get();
    }




}
